/**
 * Created by WYH on 17/4/18.
 */
angular.module('tribalc').controller(
    'ProfileController',
    ['$rootScope' ,'$scope', '$timeout','Enum', 'ElePosition', 'EleStyle', 'Api', 'CompanyModel' ,'Clone','Check','Alert',
        function ($rootScope ,$scope, $timeout, Enum, ElePosition, EleStyle, Api, CompanyModel,Clone,Check,Alert) {




        getCitys();


        $scope.isCanEdit = true;

        $scope.EleStyle = EleStyle;
        $scope.to_right_image_container = function () {
            $('#imageContainer').addClass('pro-write-picture-right')
        };
        $scope.to_left_image_container=to_left_image_container;
        function to_left_image_container() {
            $('#imageContainer').removeClass('pro-write-picture-right')
        }


        $scope.companyOptions = {
            num: Enum.companyNumberOptions,
            industry: Enum.companyIndustryOptions,
            nature: Enum.companyNatureOptions
        };

        $scope.writeStep = 0;

        $scope.nextWriteStep = nextWriteStep;
        $scope.sendVerifyCode = sendVerifyCode;
        $scope.changeBindPhone = changeBindPhone;

        $scope.uploadCompanyLogo = uploadCompanyLogo;
        $scope.uploadCompanyPictures = uploadCompanyPictures;
        $scope.uploadLegalPicture = uploadLegalPicture;


        //$scope.upload = {
        //    pictures: [],
        //    logo: null,
        //    licensePicture: null
        //};

        getUploadImage($scope.$parent.RootCompanyInfo);


// $scope.upload　=
        var uploadNumber = 0;

        setupCompanyModel();

        getCommunities();



        function getCitys() {
            Api.getChinaCitysJson(function (result) {
                $scope.citys = result;
                setCityOption()
            });
        }

        function setCityOption(){

            if($scope.citys && $scope.companyModel){
                for(var i = 0 ;i < $scope.citys.province.length;i++){
                    if($scope.citys.province[i].name == $scope.companyModel.province){
                        $scope.companyModel.provinceObj = $scope.citys.province[i]
                    }
                }

                for(var j = 0 ;j < $scope.companyModel.provinceObj.city.length;j++){
                  if($scope.companyModel.provinceObj.city[j].name == $scope.companyModel.city){
                      $scope.companyModel.cityObj = $scope.companyModel.provinceObj.city[j]
                  }
                }
                for(var k=0;k<$scope.companyModel.cityObj.county.length; k++){
                    if($scope.companyModel.cityObj.county[k].name == $scope.companyModel.district){
                        $scope.companyModel.districtObj = $scope.companyModel.cityObj.county[k]
                    }

                }


            }
        }

        function setupCompanyModel() {
            $rootScope.$watch('RootCompanyInfo', function (newCompany) {
                if (newCompany) {
                    $scope.companyModel = new CompanyModel(newCompany);
                        getUploadImage($scope.companyModel);
                        setCityOption()


                }
            })
        }

        function getCommunityIdUrl(){
           return $scope.companyModel.community ?('communities/'+ $scope.companyModel.community.id):false
        }


        function uploadLegalPicture(ele) {
            var file = ele.files[0];
            var $legalPic = $('#proLegalPicture');
            var communityIdUrl=getCommunityIdUrl();
            $('#plusImag').addClass('ng-hide')
            setupPicture($legalPic, file,function(){
                $('#plusImag').removeClass('ng-hide')
            });
            $legalPic.addClass('pro-logo-completed pro-legal-picture-content-big');

            uploadNumber++;

            uploadPicture(file,communityIdUrl, function (imgUrl) {
                $scope.upload.licensePicture = imgUrl;

            });
        }

        function uploadCompanyLogo(ele) {
            var file = ele.files[0];
            var communityIdUrl=getCommunityIdUrl();
            setupPicture($('#proLogoBox'), file);
            uploadNumber++;
            uploadLogoPicture(file,communityIdUrl, function (imgUrl) {
                $scope.$apply(function () {
                    $scope.upload.logo = imgUrl;
                });
            });
        }

        function uploadCompanyPictures(ele) {
            var $divEle = $(ele).parent();
            var file = ele.files[0];
            var communityIdUrl=getCommunityIdUrl();
            var index = $(".pro-write-picture-content .pro-write-pictures").index($($divEle).parent());
            setupPicture($($divEle), file);
            uploadNumber++;
            uploadPicture(file,communityIdUrl, function (imgUrl) {
                $scope.$apply(function () {
                    $scope.upload.pictures[index] = imgUrl;
                });
            });
        }


            function uploadLogoPicture(file,communityIdUrl, sucFuc) {
                Api.uploadLogoPicture(hex_md5(file),communityIdUrl,function (result) {
                    Api.callAliyunPicture(result.data.objectKey, result.data.url, file, function (result) {
                        uploadNumber--;
                        sucFuc(result);
                    }, function () {
                        uploadNumber--;
                    })
                }, function () {
                    uploadNumber--;
                });
            }
        function uploadPicture(file,communityIdUrl, sucFuc) {
            Api.uploadPicture(hex_md5(file),communityIdUrl,function (result) {
                Api.callAliyunPicture(result.data.objectKey, result.data.url, file, function (result) {
                    uploadNumber--;
                    sucFuc(result);
                }, function () {
                    uploadNumber--;
                })
            }, function () {
                uploadNumber--;
            });
        }


        function setupPicture($divEle ,file,cb) {
            var fileReader = new FileReader();
            fileReader.onload = function () {
                var imgSrc = fileReader.result;
                if (imgSrc) {
                    $divEle.find('img').attr("src", imgSrc);
                    $divEle.find('img').attr("src", imgSrc);
                    $divEle.addClass("pro-logo-completed");
                    if(cb){
                        cb()
                    }
                }
            };

            fileReader.readAsDataURL(file);
        }



        function submitCompanyInfo(companyInfo) {
            if (uploadNumber != 0) {
                Alert.alertBox('图片正在上传中，请稍候提交');
            } else {


                companyInfo = getValidCompanyInfo(companyInfo);
                if(!checkCompanyName($scope.companyModel.companyName)){
                    return Alert.alertBox('公司名称长度只能在4-40位字符之间')
                }
                if(!checkCmpanyAddress($scope.companyModel.address)){
                    return Alert.alertBox('公司地址长度只能在4-50位字符之间')
                }

                if(!checkPerfectInf()){
                    return Alert.alertBox('请检查必填信息是否填写')
                }
                if(!checkEmail(companyInfo.email)){
                    return Alert.alertBox('请检查邮箱格式')
                }
                if(!checkPhone(companyInfo.phone)){
                    return Alert.alertBox('固定电话格式,如：010-88776554')
                }

                if(!Check.prodesc(companyInfo.desc)){
                    return Alert.alertBox('请检查公司描述,输入字符10字-100字')
                }

                companyInfo=formatPicturePath(companyInfo);

                Api.perfectCompanyInfo(companyInfo, function (result) {
                    Alert.alertBox('完善成功',function () {
                        return window.location.reload();
                    });
                });
            }

        }

         function formatPicturePath(companyInfo) {
            var aliyu="https://buluo-gs-pictures.oss-cn-beijing.aliyuncs.com/";
            if (companyInfo.logo && companyInfo.logo.indexOf(aliyu) !== -1) {
                companyInfo.logo = "oss://" + companyInfo.logo.split(aliyu)[1];
            }
            if (companyInfo.licensePicture && companyInfo.licensePicture.indexOf(aliyu) !== -1) {
                companyInfo.licensePicture = "oss://" + companyInfo.licensePicture.split(aliyu)[1];
            }
            if (companyInfo.underCover && companyInfo.underCover.indexOf(aliyu) !== -1) {
                companyInfo.underCover = "oss://" + companyInfo.underCover.split(aliyu)[1];
            }
            if (companyInfo.pictures ){
                var pictures=[];
                for (var i=0;i<companyInfo.pictures.length;i++){
                    if( companyInfo.pictures[i].indexOf(aliyu) !== -1){
                        companyInfo.pictures[i]="oss://" + companyInfo.pictures[i].split(aliyu)[1];
                    }
                    pictures.push(companyInfo.pictures[i])
                }
                companyInfo.pictures=pictures
            }
            return companyInfo;
        }
        function checkEmail(email) {
            var state =Check.email(email)

            return state
        }
        function checkPhone(phone) {
            var pattern = /(((400)-(\d{3})-(\d{4}))|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{3,7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)$/;
            var status=true;
            if (phone && !pattern.test(phone)){
                status=false;
            }
            return status;
        }



        function getValidCompanyInfo(companyInfo) {
            companyInfo.communityId = companyInfo.community ?  companyInfo.community.id : null;
            companyInfo.communityName = companyInfo.community ? companyInfo.community.name : null;
            companyInfo.pictures = $scope.upload.pictures.length == 0 ? $rootScope.RootCompanyInfo.pictures : $scope.upload.pictures;
            companyInfo.licensePicture = !$scope.upload.licensePicture ? $rootScope.RootCompanyInfo.licensePicture :$scope.upload.licensePicture;
            companyInfo.logo = !$scope.upload.logo ? $rootScope.RootCompanyInfo.logo :$scope.upload.logo;
            companyInfo.province = companyInfo.provinceObj ? companyInfo.provinceObj.name : companyInfo.province;
            companyInfo.city = companyInfo.cityObj ? companyInfo.cityObj.name : companyInfo.city;
            companyInfo.district = companyInfo.districtObj ? companyInfo.districtObj.name : companyInfo.district;
            return companyInfo;
        }


        function sendVerifyCode(phone) {
            if (phone) {
                Api.sendPhoneVerifyCode(phone, function (result) {
                    changeVerifyCodeBtn();
                })
            } else {
                Alert.alertBox('请输入原手机号');
            }

        }


        function changeVerifyCodeBtn() {

            var wait = 60;
            forbidSendVerification();

            function forbidSendVerification() {
                if (wait == 0) {
                    $scope.verifyCodeBtn = null;
                    wait = 60;
                } else {
                    $scope.verifyCodeBtn = "重新发送(" + wait + ")";
                    wait--;
                    $timeout(function () {
                        forbidSendVerification()
                    }, 1000)
                }
            }
        }


        function changeBindPhone(oldPhone, newPhone, reNewPhone, verifyCode) {
            if (reNewPhone !== newPhone) {
                Alert.alertBox('两次新手机号输入不一致');
            } else {
                Api.changeCompanyPhone(newPhone, verifyCode, function (result) {
                    Alert.alertBox('修改手机号成功',function () {
                       return window.location.reload();
                    });
                })
            }
        }


        function nextWriteStep(number) {
            var stepNumber = $scope.writeStep + number;
            if (stepNumber < 1) {
                Alert.alertBox('已经到第一步');
            } else if (stepNumber > 3) {
                submitCompanyInfo($scope.companyModel);
            } else {
                $scope.writeStep = stepNumber;
            }
        }




        function getUploadImage(company){
            $scope.upload = {
                pictures: company ? Clone(company.pictures): [],
                logo: company? company.logo: null,
                licensePicture: company? company.licensePicture: null
            };
        }



        function getCommunities() {
            Api.getCommunityList(function (result) {
                $scope.cummunityList = result.data;
            })
        }
        function checkPerfectInf() {
            if($scope.companyModel.companyName && $scope.companyModel.community.name && $scope.companyModel.provinceObj &&
                    $scope.companyModel.cityObj && $scope.companyModel.districtObj && $scope.companyModel.address && $scope.companyModel.companyNature
            && $scope.companyModel.logo && $scope.companyModel.pictures && $scope.companyModel.linkman){
                return true;
            }else {
                return false;
            }
        }
        function checkCompanyName(value) {
            var check = (value && value.length >= 4 && value.length <= 40 );
            return check;
        }
        function checkCmpanyAddress(value) {
            var check = value && value.length >= 4 && value.length <= 50;
            return check;
        }







    }]
);